import styles from "@styles/active/activeadd.module.less";

import React, { useState, useEffect } from "react";
import { withRouter } from "react-router-dom";
import ImgCrop from "antd-img-crop";
import {
  Button,
  Form,
  Input,
  DatePicker,
  Space,
  Upload,
  Modal,
  message,
} from "antd";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import {
  layout,
  dateFormatTime,
  disabledDate,
  handleBeforeUpload,
} from "@actions/data";

const { RangePicker } = DatePicker;

function LuckyDraw({ formLuckyDraw }) {
  const [fileListActivity, setFileListActivity] = useState([]);
  const [previewImage, setPreviewImage] = useState("");
  const [previewVisible, setPreviewVisible] = useState(false);

  useEffect(() => {
    formLuckyDraw.setFieldsValue({
      activityType: 5,
      luckyDrawNumber: null,
      rules: "",
      prizeVOS: [],
      startDate: "",
      endDate: "",
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 上传图片返回按钮
  const handleCancel = () => setPreviewVisible(false);

  // 图片上传 - 图片改变
  const onChangeActivity = ({ file: { status, response }, file }, inde) => {
    console.log(file, inde);
    debugger;
    if (status !== "uploading") setFileListActivity([]);
    if (status === "done") {
      message.success("上传成功");
      setFileListActivity([
        {
          uid: file.uid,
          name: response.data.imgKey,
          status: status,
          url: response.data.imgUrl,
        },
      ]);
      formLuckyDraw.setFieldsValue({
        pictureKey: response.data.imgKey,
        pictureUrl: response.data.imgUrl,
      });
    } else if (status === "error") {
      message.error("上传失败！");
    }
  };

  // 图片上传 - 图片预览
  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    setPreviewImage(src);
    setPreviewVisible(true);
  };

  const rangepickerChange1 = (value, valueStr) => {
    formLuckyDraw.setFieldsValue({
      startDate: valueStr[0],
      endDate: valueStr[1],
    });
  };

  return (
    <Form {...layout} layout="vertical" form={formLuckyDraw}>
      <hgroup>
        <h5>基本信息</h5>
        <aside className={styles.luckdrawinfoBox}>
          <Form.Item
            name="rangepicker"
            label="活动时间"
            rules={[{ required: true, message: "请选择活动时间" }]}
          >
            <RangePicker
              showTime
              disabledDate={disabledDate}
              format={dateFormatTime}
              placeholder={["开始时间", "结束时间"]}
              onChange={rangepickerChange1}
            />
          </Form.Item>
          <Form.Item
            label="每人抽奖次数"
            name="numberLimit"
            rules={[{ required: true, message: "请输入每人抽奖次数" }]}
          >
            <Input placeholder="请输入1~999999的整数" />
          </Form.Item>
          <Form.Item
            label="兑奖规则"
            name="numberLimit"
            rules={[{ required: true, message: "请输入兑奖规则" }]}
          >
            <Input.TextArea placeholder="请输入兑奖规则" />
          </Form.Item>
        </aside>
      </hgroup>
      <hgroup>
        <h5>
          奖品设置 <span>(未中奖)</span>
        </h5>
        <aside className={styles.joinFillInfo}>奖品总数：无限制</aside>
      </hgroup>
      <hgroup>
        <h5>
          奖品设置 <span>(一等奖)</span>
        </h5>
        <aside className={styles.luckdrawBox}>
          <Form.List name="voteObjectVOS">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field, inde) => (
                  <Space
                    key={field.key}
                    align="baseline"
                    className={styles.luckdrawList}
                  >
                    <Form.Item
                      {...field}
                      wrapperCol={{ span: 18 }}
                      label={`奖品名称${field.name + 1}`}
                      name={[field.name, "name"]}
                      fieldKey={[field.fieldKey, "name"]}
                      rules={[
                        { required: true, message: "请输入投票对象的名称" },
                      ]}
                    >
                      <Input placeholder="请输入投票对象的名称" />
                    </Form.Item>
                    <Form.Item
                      {...field}
                      wrapperCol={{ span: 18 }}
                      label={`奖品总数${field.name + 1}`}
                      name={[field.name, "instructions"]}
                      fieldKey={[field.fieldKey, "instructions"]}
                      rules={[{ required: true, message: "请输入奖品总数" }]}
                    >
                      <Input placeholder="请输入奖品总数" />
                    </Form.Item>
                    <Form.Item
                      {...field}
                      wrapperCol={{ span: 18 }}
                      label={`中奖率(%)${field.name + 1}`}
                      name={[field.name, "instructions"]}
                      fieldKey={[field.fieldKey, "instructions"]}
                      rules={[{ required: true, message: "请输入中奖率" }]}
                    >
                      <Input placeholder="请输入0～100的整数" />
                    </Form.Item>
                    <Form.Item
                      label={`图片${field.name + 1}`}
                      name="pictureUrl"
                      extra="支持扩展名：jpg. jpeg. png"
                      rules={[
                        {
                          required: true,
                          message: "请选择图片",
                        },
                      ]}
                    >
                      <ImgCrop {...{ aspect: 1035 / 261 }}>
                        <Upload
                          action="/campus/campusweb/upload/pictureUpload"
                          listType="picture-card"
                          name="multipartFile"
                          fileList={fileListActivity}
                          onChange={(resp) => onChangeActivity(resp, inde)}
                          onPreview={onPreview}
                          beforeUpload={handleBeforeUpload}
                          className={styles.uploadImg}
                        >
                          {fileListActivity.length < 1 && (
                            <div>
                              <p>+</p>
                              <p>添加图片</p>
                            </div>
                          )}
                        </Upload>
                      </ImgCrop>
                    </Form.Item>
                    {fields.length > 1 ? (
                      <DeleteOutlined
                        className="dynamic-delete-button"
                        onClick={() => remove(field.name)}
                      />
                    ) : null}
                  </Space>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    添加
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
          <Modal
            visible={previewVisible}
            footer={null}
            onCancel={handleCancel}
            title="预览"
          >
            <img alt="example" style={{ width: "100%" }} src={previewImage} />
          </Modal>
        </aside>
      </hgroup>
    </Form>
  );
}

export default withRouter(LuckyDraw);
